import re
import tkinter as tk
from email import message_from_bytes
from tkinter import ttk, messagebox

from pyexpat.errors import messages

root = tk.Tk()
root.title("登录")
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width = 500
window_height = 300
x = (screen_width - window_width ) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")


frame = tk.Frame(root, padx=10, pady=80)
frame.pack()




lbl_username = tk.Label(frame, text="用户名")
username = tk.Entry(frame,validate="focusout",validatecommand=lambda: checkUsername())
lbl_username_span = tk.Label(frame, text="",width=15)
lbl_username.grid(row=0, column=0)
username.grid(row=0, column=1)
lbl_username_span.grid(row=0, column=2)





lbl_pwd = tk.Label(frame, text="密   码")
username = tk.Entry(frame,show="*")
lbl_pwd.grid(row=1, column=0)
username.grid(row=1, column=1)



login = tk.Button(frame, text="登录",command=lambda:login())
login.grid(row=2, column=0)

cancel = tk.Button(frame, text="退出",command=lambda:logout())
cancel.grid(row=2, column=1)

def logout():
    result=messagebox.askokcancel(title="提示",message="确定退出吗?")
    if result:
        root.quit()
    else:
        pass



def show():
    print("登录")
def login():
    str_name = username.get().strip()
    str_pwd = username.get().strip()
    if str_name == "admin" and str_pwd == "123456":
        main = tk.Toplevel(root)
        main.title("主窗体")
        main.geometry("900x600")
        main.grab_set()
        main.mainloop()
        # root.withdraw()

    else:
         print("登录失败")

def checkUsername():
    str_name = username.get().strip()
    if not str_name:
        return True
    else:
        # 判断用户名格式
        if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', str_name):
            lbl_username_span.config(text='用户名格式错误', fg='red')
            return False  # 验证失败返回False
        else:
            lbl_username_span.config(text='')
            return True


root.mainloop()